package com.woniu.service;

import com.woniu.dao.LoginDao;
import com.woniu.entity.RbacManager;
import com.woniu.entity.ResponseEntity;
import com.woniu.utils.JWTUtils;
import com.woniu.utils.SecurityCryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.security.auth.login.LoginException;
import java.util.concurrent.TimeUnit;

/**
 * 登录实现类 service
 *
 * @author WenXin
 * @version 1.0
 * @description: TODO
 * @date 2022/9/5 19:32
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    LoginDao loginDao;
    //    注入redis模板
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ResponseEntity login(String username, String password) throws LoginException {
        String newPassword = SecurityCryUtils.automaticallyGeneratePassword(username, password);
        RbacManager one = loginDao.findOne(username, newPassword);
        if (one != null) {
            //不给前端返回密码
            ResponseEntity responseEntity = new ResponseEntity(one);
            String token = JWTUtils.sign(username, one.getPassword());
            //将生成的token存入redis中，用于下次访问业务代码时进行认证验证
            //将token作为key,查出来的对象作为value。opsForValue相当于字符串类型 后面是过期的时间设置
            redisTemplate.opsForValue().set(token, one, 30, TimeUnit.MINUTES);

            responseEntity.putKey("token", token);

            return responseEntity;
        } else {
            //直接返回500并且设置账号或密码错误提示消息即可
            throw new LoginException("账号或密码错误！");
        }


    }

    @RequestMapping("/401")
    public ResponseEntity response401() {
        return ResponseEntity.AUTHFAILED;
    }
}
